package com.seabook.happy.website.services;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;

import javax.cache.Cache;
import javax.cache.CacheManager;

import com.google.appengine.api.images.Composite;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.seabook.happy.website.pojos.CaptchaImage;

public class SimpleCaptchaService {

	public boolean generateCaptchaImage() {
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
		Image finalImg = null;
		String captcha = "";
		try {
			byte[] imgData;
			String imgName = "WEB-INF/captcha.png";
			Cache cache = CacheManager.getInstance().getCacheFactory()
					.createCache(Collections.emptyMap());
			if (cache.containsKey(imgName)) {
				imgData = (byte[]) cache.get(imgName);
			} else {
				FileInputStream fileInputStream = new FileInputStream(imgName);
				imgData = new byte[fileInputStream.available()];
				fileInputStream.read(imgData);
				fileInputStream.close();
				cache.put(imgName, imgData);
			}
			Image bigImg = ImagesServiceFactory.makeImage(imgData);

			Random random = new Random();
			Collection<Composite> compositeArray = new ArrayList();
			int row = random.nextInt(10);

			for (int i = 0; i < 4; i++) {
				int column = random.nextInt(10);
				captcha += String.valueOf(column);
				Transform crop = ImagesServiceFactory.makeCrop(0.1f * column,
						0.1f * row, 0.1f * (column + 1), 0.1f * (row + 1));
				Image unitImg = ImagesServiceFactory.makeImage(imagesService
						.applyTransform(crop, bigImg).getImageData());
				bigImg.setImageData(imgData);
				Composite composite = ImagesServiceFactory
						.makeComposite(unitImg, i * 12 + 1, 0, 1.0f,
								Composite.Anchor.TOP_LEFT);
				compositeArray.add(composite);
			}
			
			
			finalImg = imagesService.composite(compositeArray, 50, 20, 0);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		CaptchaImage.getCaptchaImage().updateCaptchaImage(finalImg, captcha);
		return true;
	}
}
